package com.kancy.springcloudconfig.action;

import com.kancy.springcloudconfig.action.model.AlgorithmData;
import com.kancy.springcloudconfig.action.model.RefreshObject;
import com.kancy.springcloudconfig.exception.AlertException;
import com.kancy.springcloudconfig.util.MD5Util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * CipherAlgorithAction
 * </p>
 *
 * @author: kancy
 * @date: 2019/10/26 14:09
 **/
public class Md5AlgorithAction extends AbstractAlgorithmAction {

    private static Map<String, String> md5Cache = new ConcurrentHashMap();

    /**
     * 解密逻辑
     *
     * @param data
     */
    @Override
    protected String decrypt(AlgorithmData data) {
        //throw new UnsupportedFunctionException("此功能未开发，敬请期待！");
        String cipherText = data.getCipherText().trim();
        if (cipherText.length() != 16 && cipherText.length() != 32){
            throw new AlertException("MD5无效！");
        }
        if (!md5Cache.containsKey(cipherText)){
            throw new AlertException("太难了，我还没有学会怎么解密它！");
        }
        return md5Cache.get(data.getCipherText());
    }

    /**
     * 加密逻辑
     *
     * @param data
     */
    @Override
    protected String encrypt(AlgorithmData data) {
        String md5 = MD5Util.getStringMd5(data.getPlainText());
        md5Cache.put(md5, data.getPlainText());
        return md5;
    }

    @Override
    protected void update(RefreshObject object) {
        object.getPasswordObject().setVisible(false);
        object.getSaltObject().setVisible(false);
        object.getLabel1Object().setVisible(false);
        object.getLabel2Object().setVisible(false);
    }

}
